#pragma once

#include <iostream>
#include <cstring>
#include <unistd.h>

namespace Mango
{
    class Task
    {
    private:
        int sock;

    public:
        Task() : sock(-1) {}
        Task(int _sock) : sock(_sock)
        {
        }
        int Run()   //和ServiceIO函数一致
        {
            while(true)
            {
                //提供服务,我们是一个死循环
                char buffer[1024];
                memset(buffer, 0, sizeof(buffer));
                ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
                if (s > 0)
                {
                    buffer[s] = 0;   //将获取的内容当成字符串
                    std::cout << "client# " << buffer ;
                    std::string echo_string = ">>>server<<<, ";
                    echo_string += buffer;

                    write(sock, echo_string.c_str(), echo_string.size());
                }
                else if (s == 0)
                {
                    std::cout << "client quit ..." << std::endl;
                    break;
                }
                else
                {
                    std::cerr << "read error" << std::endl;
                    break;
                }
            }
            close(sock);//关闭文件描述符
        }
        int operator()() //对象() -》相当于是对象.operator() 然后去调用Run函数
        {
            Run();
        }
        ~Task() {}
    };
}